package com.ce.framework.auth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ce.util.RegeditUtil;

public class OperaUtil {
	
	static String basePath = "D:/Temp/logOpt/";
	static int maxFileSize = 10;//单位为M

	static DecimalFormat df = new DecimalFormat("000");
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	static int fileIdx = 1;
	static PrintWriter out;
	static BufferedReader in;
	static File logFile;
	
	static{
		basePath = RegeditUtil.getRegeditStringValue("SYSTEM_LOG_OP_PATH","D:/tax1.0/optLog/");
	}
	
	public static void setBasePath(String path){
		reset();
		path = path.replaceAll("\\\\", "/");
		if(!path.endsWith("/")){
			path += "/";
		}
		basePath = path;
	}
	
	public static void reset(){
		fileIdx = 1;
		if(out!=null){
			out.close();
		}
		out = null;
		if(in!=null){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		in = null;
	}
	
	public static void writeOptLog(Date dtTime,String vcSessionId,String vcUrl,String vcMethod,String vcParam,String vcHeader) throws IOException{
		PrintWriter out = getOut();
		if(out==null){
			return;
		}
		out.println(sdf.format(dtTime));
		out.println(vcSessionId);
		out.println(vcUrl);
		out.println(vcMethod);
		out.println(escape(vcParam));
		out.println(escape(vcHeader));
		out.println("-");
	}
	
	private static String escape(String str){
		return str==null?"":str.replaceAll("\r", "\\\\r").replaceAll("\n", "\\\\n");
	}

	private static PrintWriter getOut() throws IOException{
		if(out==null){
			logFile = getLogFile();
			if(logFile==null)
				return null;
			if(!logFile.getParentFile().exists()){
				logFile.getParentFile().mkdirs();
			}
			out = new PrintWriter(new FileWriter(logFile,true));
		}
		if(logFile.length()>maxFileSize*1024*1024){
			fileIdx++;
			logFile = getLogFile();
			out.flush();
			out.close();
			if(logFile==null)
				return null;
			out = new PrintWriter(new FileWriter(logFile,true));
		}
		return out;
	}
	
	private static File getLogFile(){
		File f = null;
		for(int i=1;i<=999;i++){
			f = new File(basePath+"opt-log."+df.format(i)+".txt");
			if(!f.exists() || f.length()<maxFileSize*1024*1024){
				return f;
			}
		}
		return null;
	}

}
